/**
 * 活动角色相关功能
 */
export default {
    methods: {
        /**
         * 角色授权登陆
         * @param commonToken
         * @returns {Promise<*[]|string[]|(*)[]>}
         */
        async actorAuthLoginFunc (commonToken = '') {
            console.log('[actorAuthLoginFunc]#开始执行++++++++++')
            try {
                // 刷新登陆
                let [refreshLoginError, refreshLoginResult] = await this.actorRefreshLoginFunc()
                console.log('[actorAuthLoginFunc]#刷新登陆', refreshLoginError, refreshLoginResult)
                if (refreshLoginError && refreshLoginError !== 'NotToken') {
                    return Promise.resolve([refreshLoginError, null])
                }
                if (refreshLoginResult) {
                    return Promise.resolve([null, refreshLoginResult])
                }
                // region 授权登陆 +++++
                if (!commonToken) {
                    return Promise.resolve(['未取得commonToken无法登陆', null])
                }
                // 授权接口
                if (!this.API_ACTOR_AUTH) {
                    return Promise.resolve(['授权登陆接口配置错误', null])
                }
                let [apiError, apiResult] = await this.appRequestFunc({
                    url: this.API_ACTOR_AUTH,
                    method: 'post',
                    data: {
                        main_id: this.MAIN_ID
                    },
                    headers: {
                        Authorization: 'bearer ' + commonToken
                    }
                })
                console.log('[actorAuthLoginFunc]#授权登陆信息', apiError, apiResult)
                if (apiError || apiResult.code !== 1) {
                    return Promise.resolve([apiError || apiResult.msg, null])
                }
                // 设置TOKEN
                this.setTokenFunc(apiResult.data.access_token, apiResult.data.refresh_token)
                return Promise.resolve([null, {
                    accessToken: apiResult.data.access_token,
                    refreshToken: apiResult.data.refresh_token
                }])
            } catch (exception) {
                console.log('异常[actorAuthLoginFunc]', exception)
                return Promise.resolve(['异常[actorAuthLoginFunc]', null])
            }
        },
        /**
         * 角色登陆刷新
         * @returns {Promise<({accessToken: *, refreshToken: *}|{accessToken: string, refreshToken: string}|boolean)[]|string[]|(*)[]>}
         */
        async actorRefreshLoginFunc () {
            console.log('[actorRefreshLoginFunc]#开始执行++++++++++')
            try {
                // 取得本地TOKEN
                let token = this.getTokenFunc()
                console.log('[actorRefreshLoginFunc]#获取TOKEN', token)
                if (token) {
                    // 解析TOKEN
                    let jwtPayload = this.getJwtPayloadFunc(token.accessToken)
                    console.log('[actorRefreshLoginFunc]#解析TOKEN负载', jwtPayload)
                    // 判断是否有效
                    if (jwtPayload && jwtPayload.master_id && jwtPayload.master_id == this.MAIN_ID && jwtPayload.user_type && jwtPayload.user_type == this.ACTOR_TYPE) {
                        // eslint-disable-next-line no-undef
                        if ($GP.Util.dayJS().unix() + 30 >= jwtPayload.exp) {
                            console.log('[actorRefreshLoginFunc]#TOKEN过期')
                            if (!this.API_ACTOR_TOKEN) {
                                return Promise.resolve(['刷新接口配置错误', null])
                            }
                            // 刷新TOKEN
                            let [apiError, apiResult] = await this.appRequestFunc({
                                url: this.API_ACTOR_TOKEN,
                                method: 'post',
                                data: {
                                    main_id: this.MAIN_ID,
                                    refresh_token: token.refreshToken
                                },
                                headers: {
                                    Authorization: 'bearer ' + token.accessToken
                                }
                            })
                            console.log('[actorRefreshLoginFunc]#TOKEN刷新', apiError, apiResult)
                            if (apiError || apiResult.code !== 1) {
                                // 刷新失败删除本地存储
                                this.delTokenFunc()
                                return Promise.resolve([apiError || apiResult.msg, null])
                            }
                            // 更新TOKEN
                            token.accessToken = apiResult.data.access_token
                            // 设置TOKEN
                            this.setTokenFunc(token.accessToken)
                        }
                        return Promise.resolve([null, token])
                    } else {
                        // 删除本地TOKEN
                        this.delTokenFunc()
                    }
                }
                return Promise.resolve(['NotToken', null])
            } catch (exception) {
                console.log('异常[actorRefreshLoginFunc]', exception)
                return Promise.resolve(['异常[actorRefreshLoginFunc]', null])
            }
        },
        // region 钩子调用函数 +++++
        // 角色授权登陆钩子
        async callActorAuthLoginFunc (funcParam = [], callParam = {}, resultList = []) {
            console.log('[callActorAuthLoginFunc]#参数配置：', funcParam, callParam, resultList)
            let token = ''
            if (callParam[this.appName + '@actorAuthLoginFunc']) {
                token = callParam[this.appName + '@actorAuthLoginFunc']
            } else if (callParam['accessToken']) {
                token = callParam['accessToken']
            } else {
                token = funcParam[0]
            }
            console.log('[callActorAuthLoginFunc]#授权登陆TOKEN：', token)
            if (!token) {
                return Promise.resolve(['缺少授权TOKEN参数', null])
            }
            return Promise.resolve(await this.actorAuthLoginFunc(token))
        },
        // 角色授权绑定钩子
        async callActorAuthBindFunc (funcParam = [], callParam = {}, resultList = []) {
            console.log('[callActorAuthBindFunc]#参数配置：', funcParam, callParam, resultList)
            let token = ''
            if (callParam[this.appName + '@actorAuthBindFunc']) {
                token = callParam[this.appName + '@actorAuthBindFunc']
            } else if (callParam['accessToken']) {
                token = callParam['accessToken']
            } else {
                token = funcParam[0]
            }
            if (!token) {
                return Promise.resolve(['缺少绑定TOKEN参数', null])
            }
            return Promise.resolve(await this.actorAuthBindFunc(token))
        },
        // endregion

        /**
         * 请求处理
         * @param setting
         * @returns {Promise<unknown>}
         */
        async appRequestFunc (setting = {}) {
            console.log('[appRequestFunc]#请求参数', setting)
            if (setting.loginAuth) {
                console.log('[appRequestFunc]#需要登陆认证')
                let [loginAuthError, loginAuthResult] = await this.actorRefreshLoginFunc()
                console.log('[appRequestFunc]#登陆刷新结果', loginAuthError, loginAuthResult)
                if (loginAuthError) {
                    if (this.apiLoginErrorFuncList.length) {
                        console.log('[appRequestFunc]#拦截失败执行方法', this.apiLoginErrorFuncList)
                        let resultArray = await this.onCallExecute(this.apiLoginErrorFuncList)
                        console.log('[appRequestFunc]#拦截失败执行结果', resultArray)
                    } else {
                        await this.$alert('请授权登陆')
                    }
                    setting.cancelRequest = true
                }
                // 携带TOKEN
                if (loginAuthResult) {
                    console.log('[appRequestFunc]#携带Authorization', loginAuthResult.accessToken)
                    setting.headers = setting.headers || {}
                    setting.headers = {
                        ...setting.headers,
                        ...{
                            Authorization: 'bearer ' + loginAuthResult.accessToken
                        }
                    }
                }
            }
            console.log('[appRequestFunc]#处理后请求参数', setting)
            let result = await this.safeRequestFunc(setting)
            return result
        },
        // region 认证信息处理方法 +++++
        /**
         * 设置TOKEN方法
         * @param accessToken
         * @param refreshToken
         * @returns {boolean}
         */
        setTokenFunc (accessToken = '', refreshToken = '') {
            try {
                this.setDataHubTokenFunc(accessToken, refreshToken)
                this.setLocalTokenFunc(accessToken, refreshToken)
                return true
            } catch (exception) {
                console.log('[setTokenFunc]#异常', exception)
                return false
            }
        },
        /**
         * 获取TOKEN方法
         * @returns {{accessToken: *, refreshToken: *}|boolean|{accessToken: string, refreshToken: string}}
         */
        getTokenFunc () {
            try {
                return this.getDataHubTokenFunc() || this.getLocalTokenFunc()
            } catch (exception) {
                console.log('[getTokenFunc]#异常', exception)
                return false
            }
        },
        /**
         * 删除TOKEN方法
         * @returns {boolean}
         */
        delTokenFunc () {
            try {
                this.delDataHubTokenFunc()
                this.delLocalTokenFunc()
                return true
            } catch (exception) {
                console.log('[delTokenFunc]#异常', exception)
                return false
            }
        },
        /**
         * 设置数据总线上的TOKEN
         * @param accessToken
         * @param refreshToken
         * @returns {boolean}
         */
        setDataHubTokenFunc (accessToken = '', refreshToken = '') {
            try {
                if (accessToken) {
                    let accessTokenName = this.getAccessTokenNameFunc()
                    accessTokenName && this.dataHubSet(accessTokenName, accessToken)
                }
                if (refreshToken) {
                    let refreshTokenName = this.getRefreshTokenNameFunc()
                    refreshTokenName && this.dataHubSet(refreshTokenName, refreshToken)
                }
                return true
            } catch (exception) {
                console.log('[setDataHubTokenFunc]#异常', exception)
                return false
            }
        },
        /**
         * 从数据总线获取TOKEN
         * @returns {{accessToken: *, refreshToken: *}|boolean}
         */
        getDataHubTokenFunc () {
            try {
                let accessTokenName = this.getAccessTokenNameFunc()
                let accessToken = accessTokenName && this.dataHubGet(accessTokenName, '')
                let refreshTokenName = this.getRefreshTokenNameFunc()
                let refreshToken = refreshTokenName && this.dataHubGet(refreshTokenName, '')
                if (accessToken && refreshToken) {
                    return {
                        accessToken,
                        refreshToken
                    }
                }
                return false
            } catch (exception) {
                console.log('[getDataHubTokenFunc]#异常', exception)
                return false
            }
        },
        /**
         * 从数据总线删除TOKEN
         * @returns {boolean}
         */
        delDataHubTokenFunc () {
            try {
                let accessTokenName = this.getAccessTokenNameFunc()
                accessTokenName && this.dataHubSet(accessTokenName, '')
                let refreshTokenName = this.getRefreshTokenNameFunc()
                refreshTokenName && this.dataHubSet(refreshTokenName, '')
                return true
            } catch (exception) {
                console.log('[getDataHubTokenFunc]#异常', exception)
                return false
            }
        },
        /**
         * 设置本地存储上的TOKEN
         * @param accessToken
         * @param refreshToken
         * @returns {boolean}
         */
        setLocalTokenFunc (accessToken = '', refreshToken = '') {
            try {
                if (accessToken) {
                    let accessTokenName = this.getAccessTokenNameFunc()
                    accessTokenName && window.localStorage.setItem(accessTokenName, accessToken)
                }
                if (refreshToken) {
                    let refreshTokenName = this.getRefreshTokenNameFunc()
                    refreshTokenName && window.localStorage.setItem(refreshTokenName, refreshToken)
                }
                return true
            } catch (exception) {
                console.log('[setLocalTokenFunc]#异常', exception)
                return false
            }
        },
        /**
         * 从本地存储获取TOKEN
         * @returns {{accessToken: string, refreshToken: string}|boolean}
         */
        getLocalTokenFunc () {
            try {
                let accessTokenName = this.getAccessTokenNameFunc()
                let accessToken = accessTokenName && window.localStorage.getItem(accessTokenName)
                let refreshTokenName = this.getRefreshTokenNameFunc()
                let refreshToken = refreshTokenName && window.localStorage.getItem(refreshTokenName)
                if (accessToken && refreshToken) {
                    return {
                        accessToken,
                        refreshToken
                    }
                }
                return false
            } catch (exception) {
                console.log('[getLocalTokenFunc]#异常', exception)
                return false
            }
        },
        /**
         * 从本地存储删除TOKEN
         * @returns {boolean}
         */
        delLocalTokenFunc () {
            try {
                let accessTokenName = this.getAccessTokenNameFunc()
                accessTokenName && window.localStorage.removeItem(accessTokenName)
                let refreshTokenName = this.getRefreshTokenNameFunc()
                refreshTokenName && window.localStorage.removeItem(refreshTokenName)
                return true
            } catch (exception) {
                console.log('[getLocalTokenFunc]#异常', exception)
                return false
            }
        },
        /**
         * 获取AccessToken名称
         * @returns {string}
         */
        getAccessTokenNameFunc () {
            return this.appName + '_' + this.storeAccessTokenName + '_' + this.MAIN_ID
        },
        /**
         * 获取RefreshToken名称
         * @returns {string}
         */
        getRefreshTokenNameFunc () {
            return this.appName + '_' + this.storeRefreshTokenName + '_' + this.MAIN_ID
        },
        // endregion
    }
}
